<template>
  <el-form
    ref="ruleFormRef"
    :model="slForm"
    :rules="rules"
    class="demo-ruleForm"
    label-position="top"
    size="small"
  >
    <el-form-item
      :label="t('plc.acknowledgementRequired')"
      prop="acknowledgementRequired"
    >
      <el-switch v-model="slForm.acknowledgementRequired" />
    </el-form-item>
    <el-form-item
      :label="t('plc.com')"
      prop="payload.com"
      placeholder="组件编号"
    >
      <el-input
        v-model="slForm.payload.com"
        @keyup.enter="submitForm(ruleFormRef)"
      />
    </el-form-item>

    <el-form-item>
      <el-button
        type="primary"
        @click="submitForm(ruleFormRef)"
        :disabled="!plcClientStatus"
        :loading="loading"
      >
        {{ t('plc.send') }}
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">
        {{ t('plc.reset') }}
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { sendMessageByClient, sendMessageByServer } from '@/api/plc'
import { plcStore } from '@/store/plcStore'
import { storeToRefs } from 'pinia'
import { number } from '@intlify/core-base'

const store = plcStore()
const loading = ref(false)
const { plcServerStatus, plcServerPort, plcClientStatus } = storeToRefs(store) // 连接状态

const props = defineProps({
  ip: {
    type: String,
    required: false,
    default: '127.0.0.1'
  },
  port: {
    type: Number,
    required: false,
    default: 2000
  }
})

const { t } = useI18n()
const ruleFormRef = ref<FormInstance>()

const slForm = reactive({
  acknowledgementRequired: false,
  payloadType: 'CONV',
  payload: {
    evt: 'SL',
    com: ''
  }
})

const rules = reactive<FormRules>({
  'payload.car': [
    {
      required: true,
      message: '请填写载体编号',
      trigger: 'blur'
    }
  ],
  'payload.com': [
    {
      required: true,
      message: '请填写组件编号',
      trigger: 'blur'
    }
  ]
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      loading.value = true
      sendMessageByClient(slForm).then(res => {
        ElMessage({
          showClose: true,
          message: res.data.message,
          type: 'success',
          duration: 1000
        })
      }).finally(() => {
        loading.value = false
      })
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>
